package com.qk.management.web.interceptor;


import com.qk.common.util.CurrentUserHolders;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

/**
 * @Author:gzc
 * @Date: 2025/10/06 22:10
 * @Description:
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    private static final String TOKEN_HEADER_NAME = "token";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(TOKEN_HEADER_NAME);
        Optional<String> optional = Optional.ofNullable(token);
        if (!optional.isPresent()){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
//        if (ObjectUtil.isEmpty(token)) {// token为空
//            response.setStatus(401);
//            return false;
//        }

        // 解析token，如果解析失败，返回错误结果（未登录）。
        try {
            log.info("interceptor开始解析令牌");
            Claims claims = JwtUtils.parseToken(token);
            //解析token,获取用户id,存入threadLocal
            Integer userId = claims.get("id", Integer.class);
            log.info("解析令牌成功, 获取用户id: {}", userId);
            CurrentUserHolders.setCurrentUserId(userId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求结束,删除用户id
        CurrentUserHolders.removeCurrentUserId();
    }
}
